// pages/orderPay/orderPay.js
const app = getApp();
import { $wuxKeyBoard } from '../../components/wux'   //引入安全键盘
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hidden: true,
    active: 1,  //1余额支付  2微信支付 3线下支付
    password: '', //支付密码
    isSetPass: null //是否设置过支付密码，0未设置，1已设置
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let info = JSON.parse(options.result);
    console.log(options);
    console.log(info);
    this.setData({
      info: info,
    });
  },

  onShow: function () {
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: app.baseURL + 'Mine&a=set_pay',
      data: {
        type: 2, //
        user_id: app.globalData.userId,
        order_id: this.data.info.id
      },
      success: (res) => {
        //未设置支付密码
        this.setData({
          isSetPass: res.data.info.pay_pwd,
          is_huodong: res.data.is_huodong == null ? "1" : res.data.is_huodong,  //是否是活动商品1是0否
          hidden: false,
        });
        wx.hideLoading();
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  //选择支付方式
  selectPayType(e){
    const index = e.currentTarget.dataset.index;
    this.setData({
      active: index
    })
  },

  //确认支付
  clickPay() {
    let active = this.data.active;
    //余额支付
    if (active == 2) {
      const isSetPass = this.data.isSetPass;
      if (isSetPass == 0) { 
        wx.showModal({
          title: '温馨提示',
          content: '你还未设置支付密码，去设置？',
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/passRecoverySet/passRecoverySet',
              })
            }
          }
        }); return;}
      //显示密码支付弹窗
      this.enterPay();
    } else if(active == 1) {
      //微信支付
      this.wxPay();
    } else if (active == 3) {
      const isSetPass = this.data.isSetPass;
      if (isSetPass == 0) {
        wx.showModal({
          title: '温馨提示',
          content: '你还未设置支付密码，去设置？',
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/passRecoverySet/passRecoverySet',
              })
            }
          }
        }); return;
      }
      //线下支付
      this.underLine();
    }
  },

  //微信支付
  wxPay(){
      const data = {
        user_id: app.globalData.userId,
        order_number: this.data.info.order_number,
        total_price: this.data.info.realprices,
        type:2
      };
      this.options.pid ? data.pid = this.options.pid : "";
      const dataUrl = this.options.integral == '1' ? 'Integral&a=process_Wx_pay' : 'Shopping&a=process_Wx_pay';
    wx.request({
      url: app.baseURL + dataUrl,
      data: data,
      success: (res) => {
        if (res.statusCode==200 && res.data.status == 1) {
          let wxPay = res.data.res;
          wx.requestPayment({
            'timeStamp': wxPay.timeStamp,
            'nonceStr': wxPay.nonceStr,
            'package': wxPay.package, //
            'signType': 'MD5',
            'paySign': wxPay.paySign,
            'success': (res) => {
              if (wxPay.pid && wxPay.pid != 0){
                wx.request({
                  url: app.baseURL + 'shopping&a=get_pid',
                  data: {
                    user_id: app.globalData.userId,
                    order_id: this.data.info.order_number
                  },
                  success: (res) => {
                    if (res.statusCode == 200) {
                      wx.redirectTo({ url: '../groupStatus/groupStatus?pid=' + res.data.pid })
                    }
                  }
                })
              }else{
                wx.redirectTo({
                  url: '../commentResult/commentResult?title=支付成功&tip=您已成功支付订单'
                })
              };
              wx.hideLoading();
            },
            'fail': function (res) {
            }
          })
        }
      }
    })

  },

  //余额支付弹窗-确认支付
  enterPay() {
    const thta=this;
    $wuxKeyBoard.show({
      className: 'className',
      titleText: '安全键盘',
      cancelText: '取消',
      inputText: '输入数字密码',
      showCancel: true,
      disorder: false,
      callback(value) {
        const info = thta.data.info,
        data = {
          type: 1, //支付类型，余额支付
          user_id: app.globalData.userId, //用户id
          order_id: info.id, //订单号
          price: info.realprices, //订单价格
          pwd: value //支付密码
        },
        dataUrl = thta.options.integral == '1' ? 'Integral&a=pay' : 'Shopping&a=pay';
        thta.options.pid ? data.pid = thta.options.pid:"";
        wx.request({
          url: app.baseURL + dataUrl,
          data: data,
          success: (res) => {
            if (res.statusCode == 200 && res.data.status == 1) {
              thta.setData({ paySuccess: true });
              wx.showToast({title: res.data.info,});
              if (!res.data.pid && thta.options.integral == '1'){
                wx.redirectTo({
                  url: "/pages/commentResult/commentResult?title=兑换成功&tip=你可以在兑换记录查看订单状态"
                })
              }else if(res.data.pid!=0) {
                wx.redirectTo({ url: '../groupStatus/groupStatus?pid=' + res.data.pid })
              }else{
                wx.reLaunch({ url: '../result/result' })
              }
            } else if (res.data.status != 1) {
              wx.showToast({ title: res.data.info, icon: 'none'});
            }
          },
          fail: (res) => {
            wx.showToast({ title: '网络错误', icon: 'none' })
          }
        });
      },
    })  
  },

  //线下支付
  underLine() {
    console.log(111);
    const thta = this;
    $wuxKeyBoard.show({
      className: 'className',
      titleText: '安全键盘',
      cancelText: '取消',
      inputText: '输入数字密码',
      showCancel: true,
      disorder: false,
      callback(value) {
        const info = thta.data.info,
          data = {
            type: 4, //支付类型，余额支付
            user_id: app.globalData.userId, //用户id
            order_id: info.id, //订单号
            price: info.realprices, //订单价格
            pwd: value //支付密码
          },
          dataUrl = thta.options.integral == '1' ? 'Integral&a=pay' : 'Shopping&a=pay';
        thta.options.pid ? data.pid = thta.options.pid : "";
        wx.request({
          url: app.baseURL + dataUrl,
          data: data,
          success: (res) => {
            if (res.statusCode == 200 && res.data.status == 1) {
              thta.setData({ paySuccess: true });
              wx.showToast({ title: res.data.info, });
              if (!res.data.pid && thta.options.integral == '1') {
                wx.redirectTo({
                  url: "/pages/commentResult/commentResult?title=兑换成功&tip=你可以在兑换记录查看订单状态"
                })
              } else {
                wx.reLaunch({ url: '../result/result' })
              }
            } else if (res.data.status != 1) {
              wx.showToast({ title: res.data.info, icon: 'none' });
            }
          },
          fail: (res) => {
            wx.showToast({ title: '网络错误', icon: 'none' })
          }
        });
      },
    })
  },

  // 监听页面卸载
  onUnload(){
    // !this.data.paySuccess 表示用户是没付款点击返回，true用户付款成功的跳转
    // this.options.type == 3表示从砍价页面进入的
    if (!this.data.paySuccess && this.options.type == 3) {
      // 既然已经下单，再点击返回就不需要返回商品详情页，而是直接返回到商品列表
      wx.navigateBack({
        delta: 1
      })
    } else {
      console.log(2);
    }
    
  }
})